package com.jeeplus.test.jlnu.graduationInfo.service.impl;

import cn.hutool.core.util.IdUtil;
import com.jeeplus.file.config.FileProperties;
import com.jeeplus.file.repository.AccessoryRepository;
import com.jeeplus.test.jlnu.graduationInfo.domain.entity.CustomMultipartFile;
import com.jeeplus.test.jlnu.graduationInfo.domain.entity.GraduationInfoFile;
import com.jeeplus.test.jlnu.graduationInfo.domain.vo.NewGraduationInfoReqVo;
import com.jeeplus.test.jlnu.graduationInfo.mapper.GraduationInfoFileMapper;
import com.jeeplus.test.jlnu.graduationInfo.service.GraduationInfoFileService;
import com.jeeplus.test.jlnu.graduationInfo.util.PdfSignUtil;
import com.jeeplus.test.website.websiteFile.domain.entity.WebsiteFile;
import com.jeeplus.test.website.websiteFile.service.WebsiteFileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class GraduationInfoFileServiceImpl implements GraduationInfoFileService {

    @Autowired
    private FileProperties fileProperties;

    @Autowired
    private AccessoryRepository accessoryRepository;

    @Autowired
    private GraduationInfoFileMapper graduationInfoFileMapper;
    private String FILE_SERVER = "/file";

    @Value("${config.accessory.minIO.endpoint}")
    private String systemMac;

    @Autowired
    private WebsiteFileService websiteFileService;

    @Autowired
    private PdfSignUtil pdfSignUtil;

    private MinioClient minioClient;  // MinIO客户端

    public GraduationInfoFileServiceImpl(MinioClient minioClient) {
        this.minioClient = minioClient;
    }


    @Override
    public int hooking(MultipartFile[] files, HttpServletRequest request) {
        List<String> fileNames = new ArrayList<>();
        List<GraduationInfoFile> successList=new ArrayList<>();

        for (MultipartFile file : files) {
            GraduationInfoFile graduationInfoFile = new GraduationInfoFile();
            fileNames.add(file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf(".")));
            graduationInfoFile.setCertificateName(file.getOriginalFilename().substring(0,file.getOriginalFilename().lastIndexOf(".")));
            Map<String, String> upload = upload(request, file);
            graduationInfoFile.setCertificateFile(upload.get("url"));
            graduationInfoFile.setFileType(file.getContentType());
            successList.add(graduationInfoFile);
        }
        //根据文件名找到已存在的数据
        List<GraduationInfoFile> collectnotList=graduationInfoFileMapper.findByCertificateNameList(fileNames);
        //根据文件名找到未存在却在主表中有记录的数据
        List<NewGraduationInfoReqVo> mainLists=graduationInfoFileMapper.findByCertificateNos(fileNames);
        List<GraduationInfoFile> collectInsertList=new ArrayList<>();

        List<GraduationInfoFile> changeList=successList.stream().map(vo -> {
            GraduationInfoFile graduationInfoFile = new GraduationInfoFile();
            switch(vo.getFileType()){
                case "application/pdf":
                    String insertSign="0";
                    for(GraduationInfoFile c:collectnotList){
                        if(c.getCertificateName().equals(vo.getCertificateName())){
                            if("1".equals(c.getApproveState())){
                                vo.setUploadSign("1");
                                vo.setInfoId(c.getInfoId());
                                vo.setId(c.getId());
                                vo.setCertificateType(c.getCertificateType());
                                vo.setApproveRemark(c.getApproveRemark());
                                vo.setApproveState(c.getApproveState());
                                vo.setFailReason(c.getFailReason());
                                vo.setUploadSign(c.getUploadSign());

                            }else{
                                graduationInfoFile.setFailReason("证书已通过审核，不能再次上传");
                                graduationInfoFile.setUploadSign("0");
                                graduationInfoFile.setInfoId(c.getInfoId());
                                graduationInfoFile.setId(c.getId());
                                graduationInfoFile.setCertificateType(c.getCertificateType());
                                graduationInfoFile.setCertificateName(vo.getCertificateName());
                                graduationInfoFile.setCertificateFile(vo.getCertificateFile());
                                graduationInfoFile.setApproveRemark(c.getApproveRemark());
                                graduationInfoFile.setApproveState(c.getApproveState());
                                collectInsertList.add(graduationInfoFile);
                            }

                            insertSign="1";
                            break;
                        }
                    }
                    if(insertSign.equals("0")){
                        if(mainLists.size()>0){
                            for(NewGraduationInfoReqVo ngirv:mainLists){
                                graduationInfoFile.setInfoId(ngirv.getId());
                                graduationInfoFile.setCertificateName(vo.getCertificateName());
                                graduationInfoFile.setCertificateFile(vo.getCertificateFile());

                                graduationInfoFile.setApproveState("0");
                                graduationInfoFile.setStampSign("0");
                                graduationInfoFile.setApproveState("1");
                                if(vo.getCertificateName().equals(ngirv.getCertificateNo())){
                                    graduationInfoFile.setInfoId(ngirv.getId());
                                    graduationInfoFile.setCertificateType("1");
                                    graduationInfoFile.setUploadSign("1");

                                }else if(vo.getCertificateName().equals(ngirv.getDegreeNo())){
                                    graduationInfoFile.setInfoId(ngirv.getId());
                                    graduationInfoFile.setCertificateType("2");
                                    graduationInfoFile.setUploadSign("1");
                                }
                                collectInsertList.add(graduationInfoFile);
                            }
                        }else{
                            graduationInfoFile.setCertificateName(vo.getCertificateName());
                            graduationInfoFile.setCertificateFile(vo.getCertificateFile());

                            graduationInfoFile.setApproveState("0");
                            graduationInfoFile.setStampSign("0");
                            graduationInfoFile.setApproveState("1");
                            graduationInfoFile.setUploadSign("0");
                            graduationInfoFile.setFailReason("证书名称匹配不到信息");
                            collectInsertList.add(graduationInfoFile);
                        }
                        return vo;
                    }
                    return vo;

                default: graduationInfoFile.setFailReason("文件类型错误");
                    graduationInfoFile.setUploadSign("0");
                    graduationInfoFile.setCertificateName(vo.getCertificateName());
                    graduationInfoFile.setCertificateFile(vo.getCertificateFile());
                    collectInsertList.add(graduationInfoFile);
                    return vo;
            }

        }).collect(Collectors.toList());
        //此集合走update流程
        if(collectInsertList.size()>0){
            graduationInfoFileMapper.insertGraduationInfoFile(collectInsertList);
        }
        if(changeList.size()>0){
            for(GraduationInfoFile g:changeList){
                graduationInfoFileMapper.updateGraduationInfoFile(g);
            }

        }
        return 0;

    }
    @Override
    public void approve(List<Long> ids) throws MinioException, IOException, NoSuchAlgorithmException, InvalidKeyException {
        graduationInfoFileMapper.updateFileStatus(ids);
        graduationInfoFileMapper.updatefileByInfoId(ids);
        List<GraduationInfoFile> graduationInfoFiles=graduationInfoFileMapper.findListByInfoIds(ids);
        for(GraduationInfoFile g:graduationInfoFiles){
            try {
                byte[] fileBytes = pdfSignUtil.downloadFileFromMinio(g.getCertificateFile());

                // 将字节数组转换为 MultipartFile
                MultipartFile file = new CustomMultipartFile("certificate", "certificate.pdf", "application/pdf", fileBytes);

                // 调用签名方法
                MultipartFile signedFile = pdfSignUtil.signPdf(file);

                String objectName = g.getCertificateFile();  // 上传时使用相同的文件名
                byte[] signedFileBytes = signedFile.getBytes();  // 获取签名后文件的字节数据

                // 使用 MinIO 客户端上传文件
                upload(null, new CustomMultipartFile("certificate", "certificate.pdf", "application/pdf", signedFileBytes));

            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        graduationInfoFileMapper.updateFileStatus(ids);
        graduationInfoFileMapper.updatefileByInfoId(ids);

    }
    @Override
    public void reject(List<NewGraduationInfoReqVo> graduationInfoReqVos) {
        for(NewGraduationInfoReqVo grifr:graduationInfoReqVos){
            graduationInfoFileMapper.rejectFile(grifr);
            graduationInfoFileMapper.rejectByInfoId(grifr);
        }

    }
    private Map<String, String> upload(HttpServletRequest request, MultipartFile file) {
        Calendar cal = Calendar.getInstance();
        Map<String, String> resultMap = new HashMap<>();

        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH) + 1;

        String uploadPath = "/file/test" + "/" + year + "/" + month + "/";
        String minioPath = "/test" + "/" + year + "/" + month + "/";

        // 判断文件是否为空
        if (!file.isEmpty()) {
            String name = file.getOriginalFilename();
            if (fileProperties.isAvailable(name)) {
                // 文件保存
                //accessoryRepository.save(file, uploadPath, name);
                accessoryRepository.save(file, minioPath, name);

                // 生成唯一 ID
                String fileId = IdUtil.simpleUUID();

                // 生成 URL
                String fileUrl = systemMac  + FILE_SERVER + minioPath + name;

                // 保存到数据库
                WebsiteFile websiteFile = new WebsiteFile();
                websiteFile.setId(fileId);
                websiteFile.setFileUrl(fileUrl);
                websiteFile.setFileName(name);
                websiteFile.setBucketName(uploadPath);
                websiteFile.setBucketId(FILE_SERVER);
                websiteFile.setCreateTime(new Date());
                websiteFileService.save(websiteFile);

                // 将 ID 和 URL 放入 Map
                resultMap.put("id", fileId);
                resultMap.put("url", FILE_SERVER + "/download?uploadPath=" + uploadPath + "&name=" + name);
                return resultMap;
            } else {
                resultMap.put("error", "失败");
                return resultMap;
            }
        } else {
            resultMap.put("error", "失败");
            return resultMap;
        }
    }


}
